package afk.biglog.gui;

import java.io.*;
import java.util.*;

import javax.swing.event.*;
import javax.swing.table.*;

import afk.biglog.*;

public class BlockTableModel implements TableModel
{
	private final List<Block> blocks = new ArrayList<Block>();
	private final BlockReader reader;
	private final BlockFilter filter;
	private final ErrorHandler errorHandler;

	public BlockTableModel(final BlockReader blockReader, final ErrorHandler errorHandler, final BlockFilter blockFilter)
	{
		this.reader = blockReader;
		this.errorHandler = errorHandler;
		this.filter = blockFilter;
	}

	@Override
	public int getRowCount()
	{
		return blocks.size();
	}

	@Override
	public int getColumnCount()
	{
		return 1;
	}

	@Override
	public String getColumnName(final int columnIndex)
	{
		return null;
	}

	@Override
	public Class<?> getColumnClass(final int columnIndex)
	{
		return String.class;
	}

	@Override
	public boolean isCellEditable(final int rowIndex, final int columnIndex)
	{
		return true;
	}

	@Override
	public Object getValueAt(final int rowIndex, final int columnIndex)
	{
		if ((rowIndex >= 0) & (rowIndex <= blocks.size()))
		{
			final Block block = blocks.get(rowIndex);
			try
			{
				return reader.read(block, filter);
			}
			catch (final IOException e)
			{
				errorHandler.addError("while reading block " + block, e);
			}
		}
		return "";
	}

	@Override
	public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex)
	{
		// TODO Auto-generated method stub

	}

	private final List<TableModelListener> listener = new ArrayList<TableModelListener>();

	@Override
	public void addTableModelListener(final TableModelListener l)
	{
		this.listener.add(l);
	}

	@Override
	public void removeTableModelListener(final TableModelListener l)
	{
		this.listener.remove(l);

	}

	public void addBlock(final Block block)
	{
		blocks.add(block);
		final TableModelEvent event = new TableModelEvent(this, blocks.size());
		for (final TableModelListener listener : this.listener)
			listener.tableChanged(event);
	}
}
